package v.book.read.tip.mypool;

import junit.framework.TestCase;

interface Connection {
	Object get();

	void set(Object x);
}

/**
 * 失败代理案例
 * <p>问题：只能确定 item 是否在使用，无法确定是不是当前用户（线程）在使用
 * @author 小败
 *
 */
class ConnectionImplementation implements Connection {
	public Object get() {
		return null;
	}

	public void set(Object s) {
	}
}

class ConnectionPool { // A singleton
	private static PoolManager pool = new PoolManager();

	public static void addConnections(int number) {
		for (int i = 0; i < number; i++)
			pool.add(new ConnectionImplementation());
	}

	public static Connection getConnection()
			throws PoolManager.EmptyPoolException {
		
		return new ConnectionProxy((PoolManager.PoolItem)pool.get());
	}

	public static void releaseConnection(Connection c) {
		pool.release(c);
	}
	
	private static class ConnectionProxy implements Connection {
		
		private PoolManager.PoolItem item;
		
		public ConnectionProxy(PoolManager.PoolItem item) {
			this.item = item;
		}

		public Object get() {
			if (item.inUse) {
				return null;
			}
			return item;
		}

		public void set(Object x) {
			if (item.inUse) {
				throw new RuntimeException("已被释放");
			}
		}
		
	}
}

public class ConnectionPoolDemo extends TestCase {
	static {
		ConnectionPool.addConnections(5);
	}

	public void test() {
		Connection c = null;
		try {
			c = ConnectionPool.getConnection();
		} catch (PoolManager.EmptyPoolException e) {
			throw new RuntimeException(e);
		}
		c.set(new Object());
		ConnectionPool.releaseConnection(c);
		c.get();
	}

	public static void main(String args[]) {
		junit.textui.TestRunner.run(ConnectionPoolDemo.class);
	}
} // /:~

